package com.meitianhui.convenitenbuy.module.store.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.style.TextAppearanceSpan;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.route.WalkingRouteLine;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseToolbarActivity;
import com.meitianhui.convenitenbuy.module.store.contract.StoreMapContract;
import com.meitianhui.convenitenbuy.module.store.di.DaggerStoreComponent;
import com.meitianhui.convenitenbuy.module.store.di.StoreModule;
import com.meitianhui.convenitenbuy.module.store.model.StoreInfo;
import com.meitianhui.convenitenbuy.module.store.presenter.StoreMapPresenter;
import com.meitianhui.convenitenbuy.util.TipUtils;
import com.meitianhui.convenitenbuy.util.WalkingRouteOverlay;
import com.meitianhui.convenitenbuy.widget.Spanny;

import java.util.List;

import javax.inject.Inject;

/*
 Created by Administrator on 2017/11/22.
 */

public class StoreMapActivity extends BaseToolbarActivity implements BaiduMap.OnMarkerClickListener, BaiduMap.OnMapClickListener ,StoreMapContract.View {


    private MapView mMapView;
    private TextView popupText;
    private List<StoreInfo.Convenient> mConvenientList;
    private BaiduMap mBaiduMap;
    private LocationClient mLocationClient;
    public MyLocationListenner myListener = new MyLocationListenner();
    private MyLocationConfiguration.LocationMode mCurrentMode;
    boolean isFirstLoc = true; // 是否首次定位

    @Inject
    StoreMapPresenter mStoreMapPresenter;
    private WalkingRouteLine mRoute;

    @Override
    protected int setView() {
        return R.layout.activity_store_map;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        DaggerStoreComponent.builder().storeModule(new StoreModule(this)).appComponent(App.getInstance().getAppComponent()).build().inject(this);
        isEnable(false);
        setTbTitle("雷达");
        initId();
        initData();


    }

    private void initData() {

        Intent intent = getIntent();
        mConvenientList = (List<StoreInfo.Convenient>) intent.getSerializableExtra("list");
        popupText = new TextView(StoreMapActivity.this);
        popupText.setPadding((int) getResources().getDimension(R.dimen.dp_15),
                (int) getResources().getDimension(R.dimen.dp_10),
                (int) getResources().getDimension(R.dimen.dp_15),
                (int) getResources().getDimension(R.dimen.dp_20));
        popupText.setBackgroundResource(R.drawable.popup);
        popupText.setMaxLines(3);
        popupText.setEllipsize(TextUtils.TruncateAt.END);
        popupText.setMinEms(2);
        popupText.setMaxEms(12);
        popupText.setTextColor(getResources().getColor(R.color.black));
        popupText.setTextSize(14);

        mBaiduMap = mMapView.getMap();
        mBaiduMap.setOnMarkerClickListener(this);
        mBaiduMap.setOnMapClickListener(this);
        mBaiduMap.setMyLocationEnabled(true);

        mLocationClient = new LocationClient(this);
        mLocationClient.registerLocationListener(myListener);

        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型

        mLocationClient.setLocOption(option);
        mLocationClient.start();

        mCurrentMode = MyLocationConfiguration.LocationMode.FOLLOWING;
        mBaiduMap
                .setMyLocationConfigeration(new MyLocationConfiguration(
                        mCurrentMode, true, null));

        if (mConvenientList != null){
            parseAllResultToMap(mConvenientList);//所有的商家
        }
    }

    private void parseAllResultToMap(List<StoreInfo.Convenient> convenientList) {
            mStoreMapPresenter.parseAllStore2Map(convenientList);
    }

    private void initId() {
        mMapView = getViewById(R.id.map);
    }

    @Override
    protected void onRefreshData() {

    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        mBaiduMap.hideInfoWindow();
        if (marker != null) {

            if (marker.getExtraInfo() == null) {
                return false;
            }
            String info = marker.getExtraInfo().getString("des");
            if(!TextUtils.isEmpty(info)){
                String[] d_info=info.split(",");
                String name = d_info[0];
                String address =d_info[1];
                setSpanyText(popupText, name, address);
                parseResultToMap(mConvenientList.get(Integer.parseInt(d_info[2])));
                mBaiduMap.showInfoWindow(new InfoWindow(popupText, marker.getPosition(), -47));
                MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(marker.getPosition());
                mBaiduMap.setMapStatus(update);
            }
            return true;
        } else {
            return false;
        }

    }

    private void parseResultToMap(StoreInfo.Convenient convenient) {
        mStoreMapPresenter.parseStore2Map(convenient);
    }

    /**
     * @param name
     * @param address
     */
    private void setSpanyText(TextView tv, String name, String address) {
        Spanny spanny = new Spanny(name, new TextAppearanceSpan(this, R.style.my_red_text_coupon))
                .appendText("\n")
                .append(address, new TextAppearanceSpan(this, R.style.gray_text_coupon));
        tv.setText(spanny);
    }

    @Override
    public void onMapClick(LatLng latLng) {
        mBaiduMap.hideInfoWindow();
    }

    @Override
    public boolean onMapPoiClick(MapPoi mapPoi) {
        return false;
    }

    @Override
    public void showError(String msg) {

    }

    @Override
    public void parseStore2MapSucc(MarkerOptions option) {
        mBaiduMap.addOverlay(option);
    }

    @Override
    public void showNotFind(String s) {
        TipUtils.showToast(App.getInstance(),s,3);
    }

    @Override
    public void clearBaiduMap() {
        mBaiduMap.clear();
        if (mConvenientList != null) {
            parseAllResultToMap(mConvenientList);//所有的商家
        }
    }

    @Override
    public void getOverlay(WalkingRouteResult result) {
        mRoute = result.getRouteLines().get(0);
        WalkingRouteOverlay overlay = new WalkingRouteOverlay(mBaiduMap);
        mBaiduMap.setOnMarkerClickListener(overlay);
        overlay.setData(result.getRouteLines().get(0));
        overlay.addToMap();
        overlay.zoomToSpan();
    }

    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        // 退出时销毁定位
        mLocationClient.stop();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        mMapView = null;
        super.onDestroy();
    }

    private class MyLocationListenner implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }

            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(14.0f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            }
        }
    }
}
